import React, {Component} from 'react';
import {withRouter} from 'react-router-dom'
import {Modal, Upload, message} from "antd";
import {PlusOutlined} from "@ant-design/icons";
import {baseURL} from '../../../config/index.js'
import {reqDeleteImg} from "../../../api/index.js"

// 将图片转成base64
function getBase64(file) {
  return new Promise((resolve, reject) => {
    const reader = new FileReader();
    reader.readAsDataURL(file);
    reader.onload = () => resolve(reader.result);
    reader.onerror = error => reject(error);
  });
}

class PictureWall extends Component {
  state = {
    previewVisible: false,
    previewImage: '',
    previewTitle: '',
    fileList: [],
  }
  
  render() {
    let {previewVisible, previewImage, fileList, previewTitle} = this.state
    const uploadButton = (
      <div>
        <PlusOutlined />
        <div className="ant-upload-text">Upload</div>
      </div>
    );
    return (
      <div className="clearfix">
        <Upload
          action={`${baseURL}/manage/img/upload`}
          method='post'
          name="image"
          listType="picture-card"
          fileList={fileList}
          onPreview={this.handlePreview}
          onChange={this.handleChange}
        >
          {fileList.length >= 4 ? null : uploadButton}
        </Upload>
        <Modal
          visible={previewVisible}
          title={previewTitle}
          footer={null}
          onCancel={this.handleCancel}
        >
          <img alt="example" style={{ width: '100%' }} src={previewImage} />
        </Modal>
      </div>
    );
  }
  
  componentDidMount() {
    let fileList = this.state.fileList
    if (this.props.location.state) {  //如果有值，是修改页面，改变fileList状态，渲染图片
      let {imgs} = this.props.location.state
      if (imgs) {
        imgs.forEach((item,i)=> {
          fileList[i]= {
            uid: item,
            name: item,
            status: 'done',
            url: '/upload/'+item
          }
        })
        this.setState({
          fileList
        })
      }
    }
  }
  
  // 关闭图片预览窗
  handleCancel = () => this.setState({ previewVisible: false });
  
  // 展示图片预览窗
  handlePreview = async file => {
    if (!file.url && !file.preview) {
      file.preview = await getBase64(file.originFileObj);
    }
    this.setState({
      previewImage: file.url || file.preview,
      previewVisible: true,
      previewTitle: file.name || file.url.substring(file.url.lastIndexOf('/') + 1),
    });
  };
  
  // 当图片状态改变时事件
  handleChange = async ({file, fileList }) => {
    // 上传图片
    if (file.status === 'done') {
      fileList[fileList.length-1].url = file.response.data.url
      fileList[fileList.length-1].name = file.response.data.name
    }
    
    // 删除图片
    if (file.status === 'removed') {
      let res = await reqDeleteImg(file.name)
      console.log(res)
      let {status,msg} = res
      if (status === 0){
        message.success('删除图片成功', 1)
      } else {
        message.error(msg, 1)
      }
    }
    
    // 重新设置fileList
    this.setState({ fileList },()=>{
      if (file.status === 'done' || file.status === 'removed'){
        // 将图片name数组传递给父组件
        this.props.childrenPicture(this.getFileList())
      }
    })
  };
  
  // 遍历fileList中图片name,想成数组
  getFileList = () => {
    let fileNameList = []
    this.state.fileList.forEach((item,i) => {
      fileNameList[i] = item.name
    })
    return fileNameList
  }
}

export default withRouter(PictureWall);
